package com.hotel.front;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.SharedCache;
import com.StatusTitle;
import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.BlockLogic;
import com.hotel.BL.GenericLogic;
import com.hotel.BL.RoomLogic;

import data.Block;
import data.CleaningStatus;
import data.passingData.BlockData;
import data.passingData.ResultData;

@SuppressWarnings("serial")

public class BlockService extends HttpServlet {

	//http://localhost:8080/blockService?func=addBlock&title=blockA
	//http://localhost:8080/blockService?func=editBlock&blockId=828&title=blockAB
	//http://localhost:8080/blockService?func=delBlock&blockId=828
	//http://localhost:8080/amenityService?func=changeBlock&blockId=826
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			String doClass = req.getParameter("func");
			if(doClass.equals("addBlock")){
				AddBlock(req,resp);
			}else if(doClass.equals("editBlock")){
				EditBlock(req,resp);
			}else if(doClass.equals("delBlock")){
				DeleteBlock(req,resp);
			}else if(doClass.equals("changeBlock")){
				ChangeStatus(req,resp);
			}else if(doClass.equals("getBlock4Admin")){
				GetBlock4Admin(req,resp);
			}else if(doClass.equals("getBlockById")){
				GetBlockById(req,resp);
			}else if(doClass.equals("getAllBlock")){
				GetAllBlock(req,resp);
			}else if(doClass.equals("addRoom")){
				AddRoom(req,resp);
			}else if(doClass.equals("changeTrue")){
				ChangeTrue(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void AddBlock(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{		
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		String title = req.getParameter("title");

		new BlockLogic(req,resp).AddBlock(hotelId,title);

		GetBlock4Admin(req, resp);
	}

	private void EditBlock(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long blockId = Long.parseLong(req.getParameter("id"));
		String title = req.getParameter("title");
		
		new BlockLogic(req,resp).EditBlock(blockId,title);

		GetBlock4Admin(req, resp);
	}

	private void DeleteBlock(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		String blockIdList = req.getParameter("blockId");
		long roomamount = 0;
		List<String> list = new ArrayList<String>();
		BlockLogic blockLogic = new BlockLogic(req,resp);
		for(int i = 0; i < blockIdList.split(",").length ; i++){
			long roomsize = new RoomLogic(req,resp).GetRoomByBlockId(hotelId, Long.parseLong(blockIdList.split(",")[i]));
			roomamount += roomsize;
			if(roomsize !=0){
				list.add(blockLogic.GetBlock(Long.parseLong(blockIdList.split(",")[i])).getTitle());
			}
		}
		if(roomamount == 0){
			for(int i=0;i<blockIdList.split(",").length ; i++){
				blockLogic.DeleteBlock(Long.parseLong(blockIdList.split(",")[i]));
			}
			GetBlock4Admin(req, resp);
		}else{
			
			HashMap<String,Object> returndata = new HashMap<String,Object>();
			returndata.put("data",null);
			returndata.put("cantdelete",list);
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(returndata));
		}
	}
	
	private void ChangeStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}	
		long hotelId = (Long) session.getAttribute("hotelId");
		long blockId = Long.parseLong(req.getParameter("blockId"));
		BlockLogic blockLogic = new BlockLogic(req,resp);
		boolean isFoundBlockUse = blockLogic.CanChangeBlock(hotelId,blockId);
		
		HashMap<String,Object> data = new HashMap<String,Object>();
		if(isFoundBlockUse){
			data.put("data", blockLogic.GetBlock(blockId));
			data.put("canchange", false);
		}else{
			data.put("data", blockLogic.ChangeStatus(blockId));
			data.put("canchange", true);
		}
		
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(data));
	}
	
	private void GetBlock4Admin(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long offset = Long.parseLong(req.getParameter("offset"));
		double line = Double.parseDouble(req.getParameter("line"));
		long pointer = Long.parseLong(req.getParameter("pagePointer"));
		BlockLogic blockLogic = new BlockLogic(req,resp);
		
		List<BlockData> obj = blockLogic.GetAllBlock4AdminLimit(hotelId,offset,(long)line);
		double dataSize = blockLogic.GetAllBlock4Admin(hotelId).size();
		
		Gson gson = new Gson();
		
		HashMap<String,Object> data = new HashMap<String,Object>();
		data.put("dataAmount",dataSize);
		data.put("pageNumber",pointer);
		data.put("lineAmount", line);
		data.put("pageAmount", Math.ceil(dataSize/line));
		data.put("data", obj);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(data));
	}
	
	private void GetBlockById(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		long id = Long.parseLong(req.getParameter("id"));
		Block obj = new BlockLogic(req,resp).GetBlock(id);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void GetAllBlock(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) (session.getAttribute("hotelId"));
		List<Block> obj = new BlockLogic(req,resp).GetAllBlock(hotelId);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void AddRoom(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{		
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		
		String roomName = req.getParameter("roomname");
		String roomtypeString = req.getParameter("roomtype");
		String floorString = req.getParameter("floor");
		String blockString = req.getParameter("block");
		String comment = req.getParameter("description");
		CleaningStatus a = new GenericLogic(req,resp).GetCleaningStatus(hotelId,StatusTitle.CleaningStatusTitle.CleanRooms);
		String cleaningStatusString = String.valueOf(a.getId());

		new RoomLogic(req,resp).AddRoom(hotelId,roomName,roomtypeString,floorString,blockString,comment,cleaningStatusString,0);
		SharedCache.clearHotelCacheStartWith(hotelId,"RoomLogic");

		GetBlock4Admin(req, resp);
	}
	
	//TODO: REMOVE THIS FUNCTION WHEN COMPLETE TESTING
	private void ChangeTrue(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}	
		long hotelId = (Long) session.getAttribute("hotelId");
		BlockLogic blockLogic = new BlockLogic(req,resp);
		List<Block> list = blockLogic.GetAllBlockInHotel(hotelId);
		for(int i=0;i<list.size();i++){
			Block block = list.get(i);
			block.setAvaliable(true);
			block.setStatus(true);
			blockLogic.UpdateBlock(block);
		}

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(true));
	}
}
